/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/

(function ($, owner) {

    /*
    *定义接口信息
    */
    owner.routes = {
        "app_key": "自己的KEY",
        "api_base": "https://vip.bs.wei1.top/"
    };
    /**
     * 用户登录
     **/
    owner.login = function (loginInfo, callback) {
        callback = callback || $.noop;
        loginInfo = loginInfo || {};
        loginInfo.account = loginInfo.account || '';
        loginInfo.password = loginInfo.password || '';
        if (loginInfo.account.length < 3) {
            return callback('账号最短为 3 个字符');
        }
        if (loginInfo.password.length < 6) {
            return callback('密码最短为 6 个字符');
        }
        var err = '';
        mui.ajax(owner.routes.api_base + 'api/mall.merchant/login', {
            data: {
                account: loginInfo.account,
                pwd: loginInfo.password,
                app_key: owner.routes.app_key,
                bsfrom: 'bspushapp'
            },
            async: false,
            dataType: 'json',
            type: 'post',
            timeout: 10000,//超时时间设置为10秒；
            headers: {'Content-Type': 'application/json'},
            success: function (res) {
                //服务器返回响应，根据响应结果，分析是否登录成功；
                if (res.code == 0) {
                    var token = res.data.token;
                    owner.setCache('token_merchant', token);
                    owner.setCache('bsUrls', JSON.stringify(res.data.urls))
                    return callback();
                } else {
                    err = res.msg;
                    return callback(res.msg);
                }

            },
            error: function (xhr, type, errorThrown) {
                //异常处理；
                console.log(type);
                err = '网络超时'
            }
        });
        return callback(err);

    };

    owner.createState = function (name, callback) {
        var state = owner.getState();
        state.account = name;
        state.token = "token123456789";
        owner.setState(state);
        return callback();
    };

    /**
     * 新用户注册
     **/
    owner.reg = function (regInfo, callback) {
        callback = callback || $.noop;
        regInfo = regInfo || {};
        regInfo.account = regInfo.account || '';
        regInfo.password = regInfo.password || '';
        if (regInfo.account.length < 3) {
            return callback('用户名最短需要 3 个字符');
        }
        if (regInfo.password.length < 6) {
            return callback('密码最短需要 6 个字符');
        }
        if (!checkEmail(regInfo.email)) {
            return callback('邮箱地址不合法');
        }
        var users = JSON.parse(localStorage.getItem('$users') || '[]');
        users.push(regInfo);
        localStorage.setItem('$users', JSON.stringify(users));
        return callback();
    };

    /**
     * 获取当前状态
     **/
    owner.getState = function () {
        var stateText = localStorage.getItem('$state') || "{}";
        return JSON.parse(stateText);
    };

    /**
     * 设置当前状态
     **/
    owner.setState = function (state) {
        state = state || {};
        localStorage.setItem('$state', JSON.stringify(state));
    };

    var checkEmail = function (email) {
        email = email || '';
        return (email.length > 3 && email.indexOf('@') > -1);
    };

    /**
     * 找回密码
     **/
    owner.forgetPassword = function (email, callback) {
        callback = callback || $.noop;
        if (!checkEmail(email)) {
            return callback('邮箱地址不合法');
        }
        return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
    };

    /**
     * 获取应用本地配置
     **/
    owner.setSettings = function (settings) {
        settings = settings || {};
        localStorage.setItem('$settings', JSON.stringify(settings));
    };

    /**
     * 设置应用本地配置
     **/
    owner.getSettings = function () {
        var settingsText = localStorage.getItem('$settings') || "{}";
        return JSON.parse(settingsText);
    };
    /**
     * 获取本地是否安装客户端
     **/
    owner.isInstalled = function (id) {
        if (id === 'qihoo' && mui.os.plus) {
            return true;
        }
        if (mui.os.android) {
            var main = plus.android.runtimeMainActivity();
            var packageManager = main.getPackageManager();
            var PackageManager = plus.android.importClass(packageManager)
            var packageName = {
                "qq": "com.tencent.mobileqq",
                "weixin": "com.tencent.mm",
                "sinaweibo": "com.sina.weibo"
            }
            try {
                return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
            } catch (e) {
            }
        } else {
            switch (id) {
                case "qq":
                    var TencentOAuth = plus.ios.import("TencentOAuth");
                    return TencentOAuth.iphoneQQInstalled();
                case "weixin":
                    var WXApi = plus.ios.import("WXApi");
                    return WXApi.isWXAppInstalled()
                case "sinaweibo":
                    var SinaAPI = plus.ios.import("WeiboSDK");
                    return SinaAPI.isWeiboAppInstalled()
                default:
                    break;
            }
        }
    };

    owner.setCache = function (key, value) {
        return localStorage.setItem(key, value);
    };

    owner.getCache = function (key) {
        return localStorage.getItem(key);
    };

    owner.delCache = function (key) {
        return localStorage.removeItem(key)
    };

    //个推绑定
    owner.bind_cid = function (isUnbind) {
        //此时检测是否有开启通知权限
        owner.check_notify_auth();
        var token = owner.getCache('token_merchant');
        // 获取客户端标识信息
        var info = plus.push.getClientInfo();
        if (token && info) {
            mui.ajax(owner.routes.api_base + 'api/mall.merchant/bind_cid', {
                data: {
                    cid: info.clientid,
                    token: token,
                    isUnbind: isUnbind ? 1 : 0,
                    app_key: owner.routes.app_key,
                    bsfrom: 'bspushapp'
                },

                dataType: 'json',//服务器返回json格式数据
                type: 'post',//HTTP请求类型
                timeout: 10000,//超时时间设置为10秒；
                headers: {'Content-Type': 'application/json'},
                success: function (res) {
                    //res = JSON.parse(res)
                    //console.log('bindcid',JSON.stringify(res))
                    mui.toast(res.msg)
                    if (res.code == 401) {
                        owner.delCache('token_merchant');
                        $.openWindow({
                            url: 'login.html',
                            id: 'login',
                            show: {
                                aniShow: 'pop-in'
                            },
                            waiting: {
                                autoShow: false
                            }
                        });
                    }
                },
                error: function (xhr, type, errorThrown) {
                    //异常处理；
                    alert('网络异常');
                    console.log(type);
                }
            });
        }
    };
    //检查是否开启了通知权限，android
    owner.check_notify_auth = function () {

        if (mui.os.android) {
            var main = plus.android.runtimeMainActivity();
            //包名
            var pkName = main.getPackageName();
            var NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");

            var packageNames = NotificationManagerCompat.from(main);

            if (packageNames.areNotificationsEnabled()) {
                console.log('已开启通知权限');
            } else {
                mui.confirm('通知权限没有开启，无法接收到消息通知', '需要权限提示', ['取消', '去开启'], function (e) {
                    e.index
                    if (e.index == 1) {
                        var Intent = plus.android.importClass('android.content.Intent');
                        var Build = plus.android.importClass("android.os.Build");

                        //android 8.0引导
                        if (Build.VERSION.SDK_INT >= 26) {
                            var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
                            intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
                        } else if (Build.VERSION.SDK_INT >= 21) {
                            //android 5.0-7.0
                            var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
                            intent.putExtra("app_package", pkName);
                            intent.putExtra("app_uid", uid);
                        } else {
                            //(<21)其他--跳转到该应用管理的详情页
                            var Settings = plus.android.importClass("android.provider.Settings");
                            var Uri = plus.android.importClass("android.net.Uri");
                            var intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            var uri = Uri.fromParts("package", main.getPackageName(), null);
                            intent.setData(uri);
                        }
                        // 跳转到该应用的系统通知设置页
                        main.startActivity(intent);
                    }
                }, 'div')


            }
        } else {
            console.log('ios未设置权限获取')
        }

    }
}(mui, window.app = {}));